package developer.zyk.ability.knowledge;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import developer.zyk.ability.knowledge.bo.OperateRecord;
import developer.zyk.ability.knowledge.dao.entity.ChatKnowledgeRecordDO;
import developer.zyk.ability.knowledge.dao.mappers.ChatKnowledgeRecordMapper;
import developer.zyk.ability.knowledge.common.KnowledgeUploadStatus;
import developer.zyk.global.user.bo.UserInfo;
import developer.zyk.global.util.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author zhangyongkang
 * @time 2025/5/16 13:43
 * @description
 */
@Component
public class KnowledgeClosedLoop {
    private static ChatKnowledgeRecordMapper chatKnowledgeRecordMapper;

    @Autowired
    public void setChatUnstructuredRecordMapper(ChatKnowledgeRecordMapper chatKnowledgeRecordMapper) {
        KnowledgeClosedLoop.chatKnowledgeRecordMapper = chatKnowledgeRecordMapper;
    }


    public static void record(
            Long recordId,
            OperateRecord operateRecord,
            UserInfo userInfo,
            KnowledgeUploadStatus status
    ) {
        ChatKnowledgeRecordDO chatKnowledgeRecordDO = chatKnowledgeRecordMapper.selectById(recordId);
        AssertUtil.assertNonNull(chatKnowledgeRecordDO, "文档上传记录为空");
        JSONArray recordObj = JSONUtil.parseArray(Optional.of(chatKnowledgeRecordDO).map(ChatKnowledgeRecordDO::getRecord).orElse("[]"));
        recordObj.add(operateRecord);
        chatKnowledgeRecordDO.setRecord(recordObj.toString());
        chatKnowledgeRecordDO.setStatus(status.getCode());
        chatKnowledgeRecordDO.setStatusText(status.getName());
        chatKnowledgeRecordMapper.updateById(chatKnowledgeRecordDO);
    }
}
